package com.dlc.yunguang.activity;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.dlc.commonlibrary.utils.LogPlus;
import com.dlc.commonlibrary.widget.TitleBar;
import com.dlc.yunguang.base.BaseActivity;
import com.dlc.yunguang.helper.UserHelper;
import com.dlc.yunguang.net.bean.LoginBean;
import com.dlc.yunguang.net.protocol.UserProto;
import com.dlc.yunguang.R;
import com.lzy.okgo.model.HttpParams;

import butterknife.BindView;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by Administrator on 2017/7/18 0018.
 */

public class ChangeNicknameActivity extends BaseActivity {

    @BindView(R.id.titleBar) TitleBar titleBar;
    @BindView(R.id.btn_submit) Button btn_submit;
    @BindView(R.id.et_nickName) EditText et_nickName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        titleBar.leftExit(this);

        et_nickName.setText(UserHelper.get().getNickname());
        et_nickName.setSelection(et_nickName.length());

        btn_submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String nickName = et_nickName.getText().toString().trim();
                if (TextUtils.isEmpty(nickName)) {
                    showOneToast("请填写新昵称!");
                    return;
                }
                updateNickName(nickName);
            }
        });
    }

    @Override
    protected int getLayoutID() {
        return R.layout.activity_change_nickname;
    }

    private void updateNickName(String nickName) {
        HttpParams params = new HttpParams();
        params.put("nickname", nickName);
        UserProto.get().updateUserInfo(params).
            subscribeOn(Schedulers.io()).
            observeOn(AndroidSchedulers.mainThread()).
            subscribe(new Observer<LoginBean>() {
                @Override
                public void onCompleted() {

                }

                @Override
                public void onError(Throwable e) {
                    LogPlus.e(e.getMessage());
                }

                @Override
                public void onNext(LoginBean loginBean) {
                    showToast("更新成功!");
                    UserHelper.get().saveUserInfo(loginBean);
                    setResult(RESULT_OK);
                    finish();
                }
            });
    }
}
